package exam.wzb.jsp.controller;

import exam.wzb.jsp.model.Book;
import exam.wzb.jsp.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping()
public class BookController {
    private BookService bookService;

    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @GetMapping
    public String listBooks(String name, Model model) {
        List<Book> books = bookService.findBooksByName(name);
        model.addAttribute("books", books);
        return "bookList"; // 假设JSP视图名为bookList.jsp
    }

    @GetMapping("/delete/{id}")
    public String deleteBook(@PathVariable Integer id) {
        bookService.deleteBookById(id);
        return "redirect:/books"; // 重定向到书籍列表页面
    }

    @GetMapping("/books")
    public String listBooks(@RequestParam(defaultValue = "0") int pageNo, Model model) {
        int pageSize = 10; // 每页显示的书籍数量
        int offset = pageNo * pageSize;
        List<Book> books = bookService.getBooksByPage(offset, pageSize);
        model.addAttribute("books", books);
        // ... 其他逻辑，如计算总页数等 ...
        return "books"; // 返回视图名称
    }
}
